<script setup lang="ts">
import type { ContractInfoDetail } from '@/api/types/finance'
import type { InfoItem } from '@/components/DetailCard.vue'
import { onPullDownRefresh } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getContractInfoDetail } from '@/api/finance'
import DetailCard from '@/components/DetailCard.vue'
import { getStatusName } from '@/constants/enums'
import { useFlow } from '@/hooks/useFlow'
import useLoading from '@/hooks/useLoading'

definePage({
  style: {
    navigationBarTitleText: '合同详情',
    backgroundColor: '#f5f5f5',
    enablePullDownRefresh: true,
  },
})

// 获取页面参数
const processInstanceId = ref<string>('')
const flowIdValue = ref<string>('')
const idValue = ref<string>('')

// 使用流程hook
const {
  currentProcess,
  getProcessInstance,
  getCurrentUserPendingTaskId,
  loading: flowLoading,
} = useFlow()

// 业务ID
const businessId = computed(() => {
  if (currentProcess.value?.businessKey) {
    return currentProcess.value.businessKey
  }
  if (currentProcess.value?.formVariables?.BUSINESS_KEY) {
    return currentProcess.value.formVariables.BUSINESS_KEY
  }
  return ''
})

// 合同详情数据
const contractDetail = ref<ContractInfoDetail | null>(null)
const contractDetail1 = ref<ContractInfoDetail | null>(null)
const { loading: detailLoading, startLoading: startDetailLoading, endLoading: endDetailLoading } = useLoading(false)
const error = ref(false)

// 整体加载状态（包括流程和详情）
const loading = computed(() => flowLoading.value || detailLoading.value)

// 合同状态映射
const contractStatusMap: Record<string, string> = {
  '01': '签约中',
  '02': '执行中',
  '03': '结算中',
  '04': '已完成',
}

// 格式化日期
function formatDate(dateStr: string): string {
  if (!dateStr)
    return '-'
  const date = new Date(dateStr)
  if (Number.isNaN(date.getTime()))
    return dateStr

  // 获取各个时间组件
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  // 返回 "YYYY-MM-DD" 格式
  return `${year}-${month}-${day}`
}

// 格式化日期时间
function formatDateTime(dateStr: string): string {
  if (!dateStr)
    return '-'
  const date = new Date(dateStr)
  if (Number.isNaN(date.getTime()))
    return dateStr

  // 获取各个时间组件
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')

  // 返回 "YYYY-MM-DD HH:mm:ss" 格式
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

// 获取流程实例信息
async function fetchProcessInfo(id: string) {
  try {
    await getProcessInstance(id)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }
    // 流程信息获取成功后，自动获取业务详情
    if (businessId.value) {
      await fetchContractDetail(businessId.value)
    }
  }
  catch (error) {
    console.error('获取流程信息失败:', error)
    uni.showToast({
      title: '获取流程信息失败',
      icon: 'none',
    })
  }
}

// 获取合同详情数据
async function fetchContractDetail(id?: string) {
  const contractId = id || businessId.value
  if (!contractId)
    return

  startDetailLoading()
  error.value = false

  try {
    const data = await getContractInfoDetail(contractId)
    contractDetail.value = data.data || null
  }
  catch (err) {
    console.error('获取合同详情失败:', err)
    error.value = true
  }
  finally {
    endDetailLoading()
  }
}

// 合同基本信息
const contractBasicInfo = computed<InfoItem[]>(() => {
  if (!contractDetail.value)
    return []

  return [
    {
      label: '合同编号',
      value: contractDetail.value.contractNo || '-',
      key: 'contractNo',
    },
    {
      label: '合同名称',
      value: contractDetail.value.contractName || '-',
      key: 'contractName',
    },
    {
      label: '项目编号',
      value: contractDetail.value.projectNo || '-',
      key: 'projectNo',
    },
    {
      label: '合同状态',
      value: contractStatusMap[contractDetail.value.contractStatus] || contractDetail.value.contractStatus || '-',
      key: 'contractStatus',
      type: 'status',
    },
    {
      label: '审批状态',
      value: getStatusName('advanceApprovalStatus', contractDetail.value.approvalStatus) || '-',
      key: 'approvalStatus',
      type: 'status',
    },
    {
      label: '合同开始时间',
      value: formatDate(contractDetail.value.contractStartTime),
      key: 'contractStartTime',
      type: 'date',
    },
    {
      label: '合同结束时间',
      value: formatDate(contractDetail.value.contractEndTime),
      key: 'contractEndTime',
      type: 'date',
    },
    {
      label: '支付方式',
      value: contractDetail.value.paymentMethod_dictText || contractDetail.value.paymentMethod || '-',
      key: 'paymentMethod',
    },
  ]
})

// 甲方信息
const partyAInfo = computed<InfoItem[]>(() => {
  if (!contractDetail.value)
    return []

  return [
    {
      label: '甲方名称',
      value: contractDetail.value.partyA || '-',
      key: 'partyA',
    },
    {
      label: '甲方联系方式',
      value: contractDetail.value.contactInformationPartyA || '-',
      key: 'contactInformationPartyA',
    },
    {
      label: '甲方地址',
      value: contractDetail.value.addressPartyA || '-',
      key: 'addressPartyA',
    },
    {
      label: '甲方签约日期',
      value: formatDate(contractDetail.value.dateSignaturePartyA),
      key: 'dateSignaturePartyA',
      type: 'date',
    },
    {
      label: '甲方代表',
      value: contractDetail.value.partyARepresentative || '-',
      key: 'partyARepresentative',
    },
    {
      label: '甲方开户行',
      value: contractDetail.value.partyABankDeposit || '-',
      key: 'partyABankDeposit',
    },
    {
      label: '甲方银行账号',
      value: contractDetail.value.partyABankAccount || '-',
      key: 'partyABankAccount',
    },
  ]
})

// 乙方信息
const partyBInfo = computed<InfoItem[]>(() => {
  if (!contractDetail.value)
    return []

  return [
    {
      label: '乙方名称',
      value: contractDetail.value.partyB || '-',
      key: 'partyB',
    },
    {
      label: '乙方联系方式',
      value: contractDetail.value.contactInformationPartyB || '-',
      key: 'contactInformationPartyB',
    },
    {
      label: '乙方地址',
      value: contractDetail.value.addressPartyB || '-',
      key: 'addressPartyB',
    },
    {
      label: '乙方签约日期',
      value: formatDate(contractDetail.value.dateSignaturePartyB),
      key: 'dateSignaturePartyB',
      type: 'date',
    },
    {
      label: '乙方代表',
      value: contractDetail.value.partyBRepresentative || '-',
      key: 'partyBRepresentative',
    },
    {
      label: '乙方开户行',
      value: contractDetail.value.partyBBankDeposit || '-',
      key: 'partyBBankDeposit',
    },
    {
      label: '乙方银行账号',
      value: contractDetail.value.partyBBankAccount || '-',
      key: 'partyBBankAccount',
    },
  ]
})

// 创建人信息
const creatorInfo = computed<InfoItem[]>(() => {
  if (!contractDetail.value)
    return []

  return [
    {
      label: '创建人',
      value: contractDetail.value.createName || '-',
      key: 'createName',
    },
    {
      label: '创建时间',
      value: formatDateTime(contractDetail.value.createTime),
      key: 'createTime',
      type: 'datetime',
    },
    {
      label: '更新人',
      value: contractDetail.value.updateName || '-',
      key: 'updateName',
    },
    {
      label: '更新时间',
      value: formatDateTime(contractDetail.value.updateTime),
      key: 'updateTime',
      type: 'datetime',
    },
  ]
})

// 附件统计信息
const attachmentStats = computed(() => {
  if (!contractDetail.value || !contractDetail.value.attachments)
    return []

  const attachments = contractDetail.value.attachments
  const totalCount = attachments.length
  const imageCount = attachments.filter(att => att.fileType?.includes('image')).length
  const documentCount = attachments.filter(att =>
    att.fileType?.includes('pdf')
    || att.fileType?.includes('word')
    || att.fileType?.includes('excel'),
  ).length

  return [
    {
      label: '附件总数',
      value: totalCount,
      key: 'totalAttachments',
    },
    {
      label: '图片数量',
      value: imageCount,
      key: 'imageAttachments',
    },
    {
      label: '文档数量',
      value: documentCount,
      key: 'documentAttachments',
    },
  ]
})

// 页面加载时获取数据
onLoad((e: any) => {
  console.log('页面参数:', e)
  processInstanceId.value = e?.id || ''
  flowIdValue.value = e?.flowId || ''
  idValue.value = e?.id || ''
  if (processInstanceId.value) {
    fetchProcessInfo(processInstanceId.value)
  }
  else {
    uni.showToast({
      title: '页面参数错误',
      icon: 'none',
    })
  }
})

// 下拉刷新
onPullDownRefresh(async () => {
  // 如果有流程实例ID，通过流程刷新数据
  if (processInstanceId.value) {
    await fetchProcessInfo(processInstanceId.value)
  }
  uni.stopPullDownRefresh()
})
</script>

<template>
  <view class="container bg-gray-100 py-1">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />
    <!-- 加载状态 -->
    <view v-if="loading" class="min-h-screen flex items-center justify-center">
      <view class="flex flex-col items-center">
        <wd-loading />
        <text class="mt-4 text-gray-500">加载中...</text>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="error" class="min-h-screen flex items-center justify-center">
      <view class="flex flex-col items-center p-6">
        <text class="mt-4 text-base text-gray-500">加载失败</text>
        <button
          class="mt-6 rounded-full bg-blue-500 px-6 py-2 text-white"
          @click="() => {
            if (businessId) {
              fetchContractDetail(businessId)
            }
          }"
        >
          重新加载
        </button>
      </view>
    </view>

    <!-- 正常状态 -->
    <view v-else-if="contractDetail1">
      <!-- 合同基本信息 -->
      <DetailCard
        title="合同基本信息"
        :info-list="contractBasicInfo"
        class="mx-4 mt-4"
      />

      <!-- 甲方信息 -->
      <DetailCard
        title="甲方信息"
        :info-list="partyAInfo"
        class="mx-4 mt-4"
      />

      <!-- 乙方信息 -->
      <DetailCard
        title="乙方信息"
        :info-list="partyBInfo"
        class="mx-4 mt-4"
      />

      <!-- 附件信息 -->
      <DetailCard
        v-if="contractDetail.attachments && contractDetail.attachments.length > 0"
        title="附件列表"
        :info-list="attachmentStats"
        class="mx-4 mt-4"
      />

      <!-- 创建人信息 -->
      <DetailCard
        title="创建人信息"
        :info-list="creatorInfo"
        class="mx-4 mt-4"
      />
    </view>

    <!-- 空状态 -->
    <view v-else class="flex flex-1 items-center justify-center">
      <view class="flex flex-col items-center p-6">
        <wd-status-tip image="content" tip="暂无内容" />
      </view>
    </view>
    <!-- 审批操作栏 -->
    <ApprovalActionBar v-if="flowIdValue && currentProcess?.status === 1" :process-id="flowIdValue" />
  </view>
</template>

<style scoped>
/* 页面样式 */
.page {
  background-color: #f5f5f5;
}

/* 加载动画 */
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 响应式适配 */
/* #ifdef H5 */
.page {
  min-height: 100vh;
}
/* #endif */

/* #ifdef MP-WEIXIN */
.page {
  min-height: 100vh;
}
/* #endif */

/* #ifdef APP-PLUS */
.page {
  min-height: 100vh;
}
/* #endif */
</style>
